import request from './request';
var jweixin = require( 'jweixin-module' );
import {
	getUrlparams
} from './tools.js'
import {
	wxAuthUrl
} from '../config/wxAuthUrl.js'

export default {
	//判断是否在微信中  
	isWechat: function() {
		var ua = window.navigator.userAgent.toLowerCase();
		if ( ua.match( /micromessenger/i ) == 'micromessenger' ) {
			return true;
		} else {
			return false;
		}
	},
	//初始化sdk配置  
	initJssdk: function() {
		return new Promise( ( resolve, reject ) => {
			let url = location.href.split( '#' )[ 0 ]
			let code = getUrlparams( 'code' )
			if ( code ) {
				request( {
					url: '',
					method: 'POST',
					data: {
						code: code,
						url: url,
						checkSubscribe: true
					}
				} ).then( res => {
					jweixin.config( {
						debug: false,
						appId: res.data.appId,
						timestamp: res.data.timestamp,
						nonceStr: res.data.nonceStr,
						signature: res.data.signature,
						jsApiList: [
							'checkJsApi',
							'onMenuShareTimeline',
							'onMenuShareAppMessage',
							'onMenuShareQQ',
							'onMenuShareWeibo',
							'onMenuShareQZone',
							'hideMenuItems',
							'showMenuItems',
							'hideAllNonBaseMenuItem',
							'showAllNonBaseMenuItem',
							'translateVoice',
							'startRecord',
							'stopRecord',
							'onVoiceRecordEnd',
							'playVoice',
							'onVoicePlayEnd',
							'pauseVoice',
							'stopVoice',
							'uploadVoice',
							'downloadVoice',
							'chooseImage',
							'previewImage',
							'uploadImage',
							'downloadImage',
							'getNetworkType',
							'openLocation',
							'getLocation',
							'hideOptionMenu',
							'showOptionMenu',
							'closeWindow',
							'scanQRCode',
							'chooseWXPay',
							'openProductSpecificView',
							'addCard',
							'chooseCard',
							'openCard'
						]
					} );
					jweixin.ready( () => {
						resolve( res )
					} )
					jweixin.error( ( err ) => {
						reject( err )
					} )
				} )
			} else {
				location.href = wxAuthUrl( encodeURIComponent( url ) )
				reject( {
					errMsg: '获取code失败'
				} )
			}
		} )
	},
	share: function( data ) {
		return new Promise( ( resolve, reject ) => {
			this.initJssdk().then( ( signData ) => {
				var shareData = {
					title: data && data.title ? data.title : signData.site_name,
					desc: data && data.desc ? data.desc : signData.site_description,
					link: data.url,
					imgUrl: data && data.img ? data.img : signData.site_logo,
					success: function( res ) {
						//用户点击分享后的回调，这里可以进行统计，例如分享送金币之类的  
						resolve( res )
					},
					cancel: function( err ) {
						reject( err )
					}
				};
				//分享给朋友接口  
				jweixin.onMenuShareAppMessage( shareData );
				//分享到朋友圈接口  
				jweixin.onMenuShareTimeline( shareData );
			} ).catch( err => {
				reject( err )
			} )
		} )

	}
}
